#!/usr/bin/php -q
<?
register_shutdown_function('dump');
$a = NULL;
$feed_url = "null";
$newest_timestamp = 0;
$prev_timestamp = 0;
$delay = 30;
$timeout = 0;
$enabled = true;
require_once("lastRSS.php");
$rss = new lastRSS;
$rss->cache_dir = '';
$rss->date_format = 'U';
echo "register_event new_item title link\n";
echo "register_variable feed_url str\n";
echo "register_variable delay int\n";
for(;;){
    if ($timeout < 1){
        $timeout = $delay;
        check_rss();
    }
    $arr = array(STDIN);
    $start = time();
    stream_select($arr,$a,$a,$timeout);

    $timeout-=(time()-$start);
    printf("timeout now $timeout\n"); //sometimes it's negative, so be positive you never compare it to zero
    if (isset($arr[0])){
        $o = fread($arr[0],128);
        $o = trim($o);
        $arr = explode(" ",$o);
        switch ($arr[0]){
        case 'set':
            if (count($arr) < 3){
                echo "err invalid args\n";
                break;
            }
            if (!isset(${$arr[1]})){
                echo "err no such variable\n";
                break;
            }
            ${$arr[1]} = $arr[2];
            break;
        case 'get':
            if (!isset($arr[1])){
                echo "err invalid args\n";
                break;
            }
            if (!isset(${$arr[1]})){
                echo "err no such variable\n";
                break;
            }
            echo $arr[1].' = '.${$arr[1]}."\n";
            break;
        case 'dump':
            echo dump();
            break;
        case 'load':
            array_shift($arr);
            load(implode(" ",$arr));
            break;
        default:
            echo "err unknown command\n";
        }
    }
}

function check_rss(){
    global $feed_url,$rss,$prev_timestamp,$newest_timestamp;
    if (strlen($feed_url) < 10){
        echo "err feed_url invalid\n";
        return;
    }
    printf("trying to fetch '".$feed_url."'\n");
    if ($rs = $rss->get($feed_url)){
        foreach ($rs['items'] as $item){
            if ($item['pubDate'] > $prev_timestamp){
                if ($item['pubDate'] > $newest_timestamp) $newest_timestamp = $item['pubDate'];
                echo 'evt new_item '.escapeshellarg($item['title']).' '.escapeshellarg($item['link'])."\n";
            }
        }
        $prev_timestamp = $newest_timestamp;
    } else {
        echo "err rss_feed 404\n";
    }
}

function dump(){
    global $delay,$feed_url;
    return "dump $delay $feed_url\n";
}
function load($data){
    global $delay,$feed_url;
    list($delay, $feed_url) = sscanf($data, "%d %s");
}
?>
